#include "MessageQueue.h"
#include <iostream>
MessageQueue::MessageQueue()
{
}

void MessageQueue::AddMessage(GameMessage* gm)
{
	MutexLocker ml(&m_mutex);
 	m_q.push(PGameMessage(gm));
}

void MessageQueue::Update()
{
	MutexLocker ml(&m_mutex);
	MaxLagTime();
	while(!m_q.empty() && m_q.top()->GetTimeDiff() >= m_maxLagTime)
	{
		m_q.top()->Execute();
		m_q.pop();
	}
	//std::cout << "Finished update msg queue" << std::endl;
}

void MessageQueue::Clear()
{
	MutexLocker ml(&m_mutex);

	while(!m_q.empty())
	{
		m_q.pop();
	}
}

void MessageQueue::AddLagTime(unsigned int lag)
{
	MutexLocker ml(&m_mutex);
	m_lagTimes.push(lag);
	m_maxLagTime = 0;
	//std::cout << "lag: " << lag << std::endl;
}

void MessageQueue::MaxLagTime()
{
	MutexLocker ml(&m_mutex);
	while(!m_lagTimes.empty())
	{
		if (m_maxLagTime <= m_lagTimes.top())
		{
			m_maxLagTime = m_lagTimes.top();
		}
		m_lagTimes.pop();
	}
}